package com.xxlie.auth.endpoint;

import com.xxlie.core.model.Page;
import com.xxlie.core.model.Query;
import com.xxlie.auth.common.exception.enums.ParamExceptionEnums;
import com.xxlie.auth.interceptor.OperationLog;
import com.xxlie.auth.service.DictService;
import com.xxlie.auth.domain.Dict;

import com.xxlie.core.model.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 *
 * @author xxlie.com
 * @since 2017/7/30
 */
@RestController
@RequestMapping("/api/sys/dict")
public class DictEndpoint {

    @Autowired
    private DictService dictService;

    @RequestMapping(value = "type")
    public View<List<String>> findTypeList() {
        List<String> typeList = dictService.findTypeList();
        View<List<String>> view = View.ofOk();
        view.setData(typeList);
        return view;
    }

    @RequestMapping(value = {"list", "search"})
    public View<Page<Dict>> search(@RequestBody Query<Dict> query) {

        Dict dict = query.getData();
        Page<Dict> page = dictService.find(new Page<Dict>(query.getPage(), query.getSize()), dict);
        View<Page<Dict>> view = View.ofOk();
        view.setData(page);
        return view;

    }

    @RequestMapping(value = {"findListByQuery"})
    public View<List<Dict>> findListByType(@RequestBody Query<Dict> query) {

        Dict dict = query.getData();
        List<Dict> dicts = dictService.find(dict);
        View<List<Dict>> view = View.ofOk();
        view.setData(dicts);
        return view;
    }

    @RequestMapping("findOne/{id}")
    public View<Dict> findOne(@PathVariable("id") Long id) {
        View<Dict> view = View.ofOk();
        Dict duties;
        if (id != null) {
            duties = dictService.findOne(id);
        } else {
            duties = new Dict();
        }
        view.setData(duties);
        return view;
    }

    @OperationLog
    @RequestMapping(value = "save")
    public View<Dict> save(@Validated @RequestBody Dict dict) {

        dictService.save(dict);
        View<Dict> view = View.ofOk("保存字典'" + dict.getLabel() + "'成功");
        view.setData(dict);
        return view;
    }

    @OperationLog
    @RequestMapping(value = "delete")
    public View<String> delete(@RequestParam Long id) {

        if (id != null) {
            dictService.delete(id);
        } else {
            return View.of(ParamExceptionEnums.PARAMS_NULL);
        }

        return View.ofOk("删除字典成功");
    }

    @OperationLog
    @RequestMapping(value = "batchDelete")
    public View<String> batchDelete(@RequestParam Long[] ids) {

        if (ids == null) {
            return new View<>(50000, "参数为空");
        }
        for (Long id : ids) {
            if (null != id) {
                dictService.delete(id);
            }
        }
        return new View<String>(20000, "删除字典成功");
    }


}
